import SwiftUI
import SwiftData

// MePage
// 我页面

struct MePage: View {
    @Environment(\.modelContext) private var modelContext
    @Query private var loginInfo: [LoginInfo]
    @Query private var userInfo: [UserInfo]
    
    @State private var showAvatarPicker: Bool = false
    
    var body: some View {
        NavigationView {
            List {
                Section {
                    MePageInfoRow(showAvatarPicker: $showAvatarPicker)
                }
                
                Section {
                    NavigationLink {
                        AccountInfoPage()
                            .onDisappear(perform: UpdateUserInfo)
                    } label: {
                        Label("账号信息", systemImage: "person.circle")
                    }
                    
                    NavigationLink {
                        RealNamePage()
                            .onDisappear(perform: UpdateUserInfo)
                    } label: {
                        Label("实名认证", systemImage: "person.text.rectangle")
                    }
                }
                
                Section {
                    NavigationLink {
                        AboutPage()
                    } label: {
                        Label("关于", systemImage: "info.circle")
                    }
                }
                
                Section {
                    Button {
                        RemoveLoginUserInfo()
                    } label: {
                        HStack {
                            Spacer()
                            Text("退出登录")
                            Spacer()
                        }
                    }
                }
            }
            .navigationTitle("我")
        }
        .sheet(isPresented: $showAvatarPicker, onDismiss: {
            UpdateUserInfo()
        }, content:{
            Avatar_Picker(userId: loginInfo.last?.userId ?? "")
        })
    }

    func UpdateUserInfo() {
        RequestUserInfo(modelContext: modelContext, userId: loginInfo.last?.userId ?? "")
    }
    
    func RemoveLoginUserInfo() {
        for info in userInfo {
           modelContext.delete(info)
        }
        for info in loginInfo {
           modelContext.delete(info)
        }
    }
}

#Preview {
    MePage()
}
